package edu.neu.agv_backend.service;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

@Service
public class AgvProxyService {

    private final RestTemplate restTemplate;

    private final String baseUrl;

    public AgvProxyService(RestTemplate restTemplate,
                           @Value("${agv.remote.base-url}") String baseUrl) {
        this.restTemplate = restTemplate;
        this.baseUrl = baseUrl;
    }

    /**
     * 转发请求到小车提供的接口
     *
     * @param request 原始 HttpServletRequest
     * @param method  请求方法
     * @return 代理后的响应
     * @throws IOException 读取请求体异常
     */
    public ResponseEntity<String> forward(HttpServletRequest request, HttpMethod method) throws IOException {
        String proxyPath = extractProxyPath(request);
        String targetUrl = baseUrl + proxyPath + (request.getQueryString() != null ? ("?" + request.getQueryString()) : "");

        HttpHeaders headers = copyRequestHeaders(request);
        String body = null;
        if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) {
            body = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
        }
        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);

        ResponseEntity<String> response = restTemplate.exchange(targetUrl, method, httpEntity, String.class);
        return new ResponseEntity<>(response.getBody(), response.getStatusCode());
    }

    private String extractProxyPath(HttpServletRequest request) {
        // /api 前缀之后的路径
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String apiPrefix = contextPath + "/api";
        return uri.substring(apiPrefix.length());
    }

    private HttpHeaders copyRequestHeaders(HttpServletRequest request) {
        HttpHeaders headers = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            // 排除 Host 等由 RestTemplate 管理的头，也可根据需要过滤
            if ("host".equalsIgnoreCase(headerName)) {
                continue;
            }
            Enumeration<String> headerValues = request.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                headers.add(headerName, headerValues.nextElement());
            }
        }
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    public ResponseEntity<String> request(String path, HttpMethod method, Object body) {
        String targetUrl = baseUrl + path;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        return restTemplate.exchange(targetUrl, method, entity, String.class);
    }
} 